﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.MainBoundedContext.StockModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Huirui.Cavan.Domain.Seedwork;
using Spring.Context.Support;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;

namespace Huirui.Cavan.Application.MainBoundedContext.StockModule
{
    public class WareHouseAppService : BaseAppService<WareHouse, string, WareHouseSearch, IWareHouseRepository>, IWareHouseAppService
    {
        private IEmployeeAppService EmployeeAppService { get; set; }

        public override BoolGenericResult<WareHouse> AddOrUpdate(WareHouse entity)
        {
            this.SpringContext = ContextRegistry.GetContext();
            BoolGenericResult<WareHouse> result = new BoolGenericResult<WareHouse>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            this.EmployeeAppService = this.SpringContext.GetObject(SystemModuleConst.EMPLOYEEAPPSERVICE) as IEmployeeAppService;
            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            StockManager stockManager = new StockManager(employee);

            WareHouse oldWareHouse = this.Repository.Get(entity.Id);
            if (oldWareHouse.IsNull())
            {
                result = stockManager.AddWareHouse(entity.Id, entity.Address, entity.Status, entity.Department, entity.Employee);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = stockManager.UpdateWareHouse(oldWareHouse, entity.Address, entity.Status, entity.Department, entity.Employee);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }
    }
}
